/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: BearingClientExample.cpp,v 1.4 2009-07-06 14:27:16 ray Exp $
 *
 * \file
 * \brief Example client for building MaCI Clients apps. (With Bearing interface)
 * \author Antti Maula <antti.maula@tkk.fi>
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string>
#include "owndebug.h"
#include "ownutils.h"
#include "binbag.h"
#include "BearingClient.hpp"

#define REPLY_WAIT 3000

//*****************************************************************************
// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************
// Choose your namespace
using namespace MaCI;
using namespace MaCI::Bearing;
//*****************************************************************************
// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************
static std::string datasource;
static std::string datasourceMaCISL;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tBearingClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tSpecify the data source\n");
  fprintf(stderr,"  \t\t\t\tOR\n");
  fprintf(stderr,"  [-S name]\t\t\tSpecify the data source by MaCISL\n\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int bearingWatch(CBearingClient *dc)
{
  CBearingData dd;
  bool r;
  unsigned int sequence = 0;
  while(run) {

    r = dc->GetBearingEvent(dd, &sequence, 5000);
    if (r) {
      dPrint(1,"Got event:");
      dd.Print(1);
    }
  }
  
  return 0;
}
//*****************************************************************************

static int ExecuteExampleClient(gimi::GIMI &g)
{
  char c,d;
  unsigned int rvalue = 0, param=0, bdata;
  ownTime_ms_t scallbegin;

  // Bearing client instance
  CBearingClient dc(&g, 0);

  // Bearing data instance
  CBearingData dd;
  dd.CreateInternalBinBag();

  // Variable for storing thread id.
  ownThreadHandle bearingWatchThread;

  // Init random generator.
  srandom(time(NULL));

  // Assign default target.
  if (datasource.size()) {
    dc.SetDefaultTarget(datasource);

  } else {
    // GIMI is Open(), so we can execute this.
    dc.SetDefaultTarget(MaCICtrl::SMaCISL(datasourceMaCISL), 10000);
    
  }
  
  // Open.
  if (dc.Open() == KMaCIOK) {
    dPrint(2,"Succesfully Open():ed BearingClient!");
    bearingWatchThread = ownThread_Create((void*)bearingWatch, &dc);
    

    //TCommand *command;
    //const TBlock block;
    while(run) {
      
      
      printf("***** MENU *****\n");
      printf("1. Get bearing\n");
      printf("2. Get power\n");
      printf("3. Set power\n");
      printf("q  Quit\n");
      printf("\n");	
      printf("What to do? ");
      c=getchar();
      d=getchar();

      printf("\n");
      if (c!=EOF) {
        switch(c) {
          
        case '1':
          //command->cmd=KCommandMeasure;
          //const TCommand cmd(KCommandMeasure);
          // Construct 'Command'
          dd.SetCommand(KCommandMeasure);
          dc.SendCommand(dd);
          break;
          
        case '2':
          param=PWR_LEVEL;
          scallbegin = ownTime_get_ms();
          if (dc.GetParamBySynchronousCall(rvalue, param, REPLY_WAIT)) {
            dPrint(1,"Got value: '%u', total time of call was: %u milliseconds",
               rvalue, ownTime_get_ms_since(scallbegin));
               
          } else {
            dPrint(1,"WTF? Synchronous call failed!");

          }
          break;
        case '3':
          printf("New value in dBm(10-27)? ");
          scanf("%d",&rvalue);
          if (rvalue>9 && rvalue<28) {
            bdata=PWR_LEVEL<<24;
            bdata+=10*(rvalue-5);
            // Construct 'Command'
            //const TCommand cmd(KCommandSetParam);
            dd.SetCommand(KCommandSetParam);
            dd.SetBlock(bdata);
            dc.SendCommand(dd);
          }
          break;
          
          //cmd.cmd=KCommandGetParam;
          //dd.SetCommand(cmd);
          //block->data=(int32_t)PWR_LEVEL<<24;
          //printf("Sending command %d with data %d\n",cmd.cmd, block.data);
          /*
            case '2':
            if (dc.GetStatusBySynchronousCall(rvalue, channel, REPLY_WAIT)) {
            dPrint(1,"Got status: '%u', total time of call was: %u milliseconds",
            rvalue, ownTime_get_ms_since(scallbegin));
            
            } else {
            dPrint(1,"WTF? Synchronous call failed!");
            
            }
            break;
            
            case '3':
            printf("current (0-4A)?");
            scanf("%f",&current);
            d=getchar();
            
            if (current<4.1) {
            // Construct 'Command'
            const TCommand cmd(KCommandSetCurrent);
            dd.SetCommand(cmd);
            const TChannel ch(channel);
            dd.SetChannel(ch);
            const TCurrent cur(current);
            dd.SetCurrent(cur);
            // Send command to Server part.
            dc.SendCommand(dd);
            }
            break;
          */
        case 'q':
  	  run=0;
          break; 
        }
      }
      /*
      // Wait for a "moment".
      const unsigned int sleepTime = 1000 + random() % 5000;
      dPrint(1,"Sleeping for %u milliseconds...", sleepTime);
      ownSleep_ms(sleepTime);
      */
    }
    
    
  } else {
    dPrint(1,"Failed to Open() BearingClient.");

  }
  
  
  return 0;
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName;

  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.4 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "n:u:p:s:S:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

    case 's':
      datasource = optarg;
      dPrint(3,"Using DataSource '%s'", optarg);
      break;

    case 'S':
      datasourceMaCISL = optarg;
      dPrint(3,"Using DataSource MaCISL '%s'", optarg);
      break;

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteExampleClient(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
 * 
 * $Log: not supported by cvs2svn $
 * Revision 1.3  2009-06-23 09:14:22  ray
 *
 * kkk
 *
 * Revision 1.2  2009-05-13 07:18:15  amaula
 * Doxygens file tag parameter removed, as no parameter means 'document this file'
 *
 * Revision 1.1  2009-04-08 14:18:01  ray
 * Initial
 *
 * Revision 1.2  2009-04-08 07:08:22  amaula
 * Merged in 'MaCI-examples-restructuring-branch'
 *
 * Revision 1.9  2009-02-05 14:17:19  ray
 * KK
 *
 * Revision 1.8  2009-01-30 11:15:56  ray
 * KK
 *
 * Revision 1.7  2009-01-23 09:45:02  ray
 * kk
 *
 * Revision 1.6  2009-01-23 09:43:02  ray
 * kkk
 *
 * Revision 1.5  2009-01-22 12:48:36  ray
 * kk
 *
 * Revision 1.4  2009-01-22 11:38:54  ray
 * kkk
 *
 * Revision 1.3  2009-01-22 10:42:12  ray
 * kkk
 *
 * Revision 1.2  2009-01-22 08:55:20  mmatusia
 * cdc
 *
 * Revision 1.1  2009-01-21 12:12:39  ray
 * Intial
 *
 * Revision 1.3  2009-01-19 11:59:05  amaula
 * Merged in branch: 'MaCI-interfaces-synchronous-messaging-replyQueue-implementation-branch'
 *
 * Revision 1.2.4.1  2009-01-19 11:45:35  amaula
 * Example Implementation for Synchronous messages complete.
 *
 * Revision 1.2  2008-12-08 09:49:23  amaula
 * Bearing updated.
 *
 * Revision 1.1  2008-12-01 12:54:43  amaula
 * Added client for Bearing interface.
 *
 * Revision 1.5  2008-11-07 11:12:46  amaula
 * Lots of misc. changes.
 *
 *
 *
 *****************************************************************************/
//*****************************************************************************
//*****************************************************************************


